package main

import (
	"fmt"
	"time"
)

func main() {
	ch := make(chan int, 10)
	ticker := time.NewTicker(1 * time.Second)
	done := make(chan bool)
	go createProducer(ch, done)
	go createConsumer(ch, ticker)
	//以下判断调节主线程等待子线程运行完成，通道关闭再退出，如果没有此判断，主线程会先退出，子线程无法得到执行
	select {
	case <-done:
		fmt.Println("已经没有数据生产")
	}
}

//Producer实现
func createProducer(ch chan<- int, done chan bool) {
	for i := 0; i < 10; i++ {
		ch <- i
		time.Sleep(1 * time.Second)
	}
	close(done)
}

//Consumer实现
func createConsumer(ch <-chan int, ticker *time.Ticker) {
	for _ = range ticker.C {
		fmt.Printf("接收到生产者数据：%v\n", <-ch)
	}
}
